package net.zio.kamenriderzioaddon.network;

import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.zio.kamenriderzioaddon.KamenRiderZioAddonMod;
import net.zio.kamenriderzioaddon.ridersystem.data.PlayerDataManager;

/**
 * 1.18.2 专用服务端事件集中处理
 */
@Mod.EventBusSubscriber(modid = KamenRiderZioAddonMod.MODID)
public final class CommonEvents {

    /* ---------- 玩家 Tick ---------- */
    @SubscribeEvent
    public static void onPlayerTick(TickEvent.PlayerTickEvent event) {
        if (event.phase != TickEvent.Phase.END) return;          // 只在 END 阶段执行
        Player player = event.player;
        if (player.level.isClientSide) return;                   // 纯服务端逻辑
        PlayerDataManager mgr = PlayerDataManager.get(player);
        if (mgr.isDirty()) {                                     // 脏标记
            mgr.sync(player);                                    // 发送单个玩家
            mgr.clearDirty();                                    // 清脏
        }
    }

    /* ---------- 登录 ---------- */
    @SubscribeEvent
    public static void onLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {
        if (event.getPlayer() instanceof ServerPlayer sp) {
            PlayerDataManager mgr = PlayerDataManager.get(sp);
            mgr.sync(sp);                                        // 全量同步
        }
    }

    /* ---------- 重生 ---------- */
    @SubscribeEvent
    public static void onRespawn(PlayerEvent.PlayerRespawnEvent event) {
        if (event.getPlayer() instanceof ServerPlayer sp) {
            PlayerDataManager mgr = PlayerDataManager.get(sp);
            mgr.sync(sp);
        }
    }

    /* ---------- 换维度 ---------- */
    @SubscribeEvent
    public static void onChangeDim(PlayerEvent.PlayerChangedDimensionEvent event) {
        if (event.getPlayer() instanceof ServerPlayer sp) {
            PlayerDataManager mgr = PlayerDataManager.get(sp);
            mgr.sync(sp);
        }
    }

    /* ---------- 死亡后拷贝数据 ---------- */
    @SubscribeEvent
    public static void onClone(PlayerEvent.Clone event) {
        if (event.isWasDeath()) {                                // 只处理真正死亡
            PlayerDataManager old = PlayerDataManager.get(event.getOriginal());
            PlayerDataManager neu = PlayerDataManager.get(event.getPlayer());
            neu.deserializeNBT(old.serializeNBT());              // 全量拷贝
            neu.sync(event.getPlayer());                         // 立即同步
        }
    }
}